package com.example.piece.ui.fragment

import android.Manifest
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.*
import com.bumptech.glide.request.transition.Transition
import com.example.base.aop.click.RepeatClick
import com.example.base.aop.login.LoginCallback
import com.example.base.aop.permission.PermissionRequest
import com.example.base.broadcast.Event
import com.example.base.broadcast.EventBusUtil
import com.example.base.ext.getViewModel
import com.example.base.ext.navigationTo
import com.example.base.ext.saveToGallery
import com.example.base.ext.setCornersPlaceHolderImageUrl
import com.example.base.tools.ConfigTool
import com.example.base.ui.fragment.BaseFragment
import com.example.base.vm.onError
import com.example.piece.App
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.FragmentUserBinding
import com.example.piece.tools.SIMCardInfo
import com.example.piece.tools.ShareUtil
import com.example.piece.vm.UserViewModel
import com.gyf.immersionbar.ktx.immersionBar
import com.kongzue.dialogx.dialogs.*
import com.kongzue.dialogx.interfaces.*
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking


class UserFragment : BaseFragment<FragmentUserBinding>() {


    companion object {
        fun newInstance(): Fragment {
            val fragment = UserFragment()
            return fragment
        }
    }

    override fun isRegisterEventBus(): Boolean = true
    private val userViewModel: UserViewModel by lazy {
        getViewModel<UserViewModel>()
    }

    override fun initData(view: View, savedInstanceState: Bundle?) {
        super.initData(view, savedInstanceState)
        mBinding.fragment = this

        if (!App.USER_TOKEN.isNullOrEmpty()) {
            getUserInfo()
        }

    }

    override fun getContentRes(): Int = R.layout.fragment_user

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            immersionBar {
                fitsSystemWindows(false)
                statusBarDarkFont(true)
                // statusBarAlpha(0.0f)
            }

            if (!App.USER_TOKEN.isNullOrEmpty()) {
                getUserInfo()
            }
        }
    }


    override fun onResume() {
        super.onResume()
        if (!App.USER_TOKEN.isNullOrEmpty()) {
            getUserInfo()
        }
    }

    override fun receiveEvent(event: Event<Any>?) {
        super.receiveEvent(event)
        when (event?.code) {
            Key.EventKey.EVENT_LOGIN -> {//登录成功
                getUserInfo()
            }
            Key.EventKey.EVENT_SINGIN -> {//签到成功
                getUserInfo()
            }
            Key.EventKey.EVENT_UPDATE_SUC -> {//信息修改成功
                getUserInfo()

            }

        }
    }


    //获取个人信息
    private fun getUserInfo() {
        userViewModel.userInfo(null) {//获取个人信息
            if (it.code == 200) {//获取个人信息
                App.userLoginCodeEntity = it.data
                setUserInfo()
            }

        } onError {

        }
    }

    private fun setUserInfo() {

        val user = App.userLoginCodeEntity.user
        mBinding.imgHead.setCornersPlaceHolderImageUrl(
            user.avatar,
            90,
            R.drawable.header_img
        )
        mBinding.tvName.text = user.nickname
        mBinding.tvSign.text = user.signature

        val info = App.userLoginCodeEntity.info
        mBinding.tvFsNum.text = info.fansNum
        mBinding.tvGzNum.text = info.attentionNum
        mBinding.tvLedouNum.text = info.experienceNum


    }

    //分享
    @RepeatClick
    fun share() {
        BottomDialog.build()
            .setCustomView(object : OnBindView<BottomDialog>(R.layout.dialog_share_app) {
                override fun onBind(dialog: BottomDialog?, v: View?) {
                    v?.findViewById<LinearLayout>(R.id.ll_wechat)?.setOnClickListener {//微信
                        context?.let { it1 -> ShareUtil.shareTextToWechat(it1, "测试") }

                    }
                    v?.findViewById<LinearLayout>(R.id.ll_wechat_friends)
                        ?.setOnClickListener {//微信朋友圈

                            getphoto()

                        }
                    v?.findViewById<LinearLayout>(R.id.ll_qq)?.setOnClickListener {//QQ
                        context?.let { it1 -> ShareUtil.shareTextToQQFriend(it1, "测试") }

                    }
                    v?.findViewById<LinearLayout>(R.id.ll_qq_zone)?.setOnClickListener {//QQ空间

                    }
                    v?.findViewById<LinearLayout>(R.id.ll_vb)?.setOnClickListener {//微博

                        context?.let { it1 -> ShareUtil.shareTextToVB(it1, "测试") }


                    }


                }

            })
            .show()
    }

    /**  点击添加图片的事件  **/
    @PermissionRequest(
        value = [
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
        ]
    )
    private fun getphoto() {
        context?.let { it1 ->
            //要在子线程中使用，否则会报错
            val dataUri = ArrayList<Uri>()
            val dataDeferred = ArrayList<Deferred<Int>>()

            var waitId = 0;
            var progress = 0F
            WaitDialog.show("正在加载",WaitDialog.TYPE.NONE).setOnBackPressedListener(object : OnBackPressedListener {
                override fun onBackPressed(): Boolean {
                    MessageDialog.show("正在进行", "是否取消？", "是", "否")
                        .setOkButton(object : OnDialogButtonClickListener<MessageDialog> {
                            override fun onClick(baseDialog: MessageDialog, v: View?): Boolean {

                                waitId = -1
                                WaitDialog.dismiss()
                                return false
                            }


                        })
                    return false
                }

            })

            runBlocking {
                val data = ArrayList<String>()
                data.add("https://tva1.sinaimg.cn/large/0080xEK2ly1gftvfumyb7g30a80gge83.gif")
                data.add("http://wx2.sinaimg.cn/large/9bd522c1ly1gfg6zsy960g206s0aahe1.gif")
                data.add("http://wx4.sinaimg.cn/large/5eef6257gy1g8qmhbxeslg207s0dqx74.gif")
                data.add("http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201602/19/32E90AB13A4841D3E1FC6233CED69B20.gif")
                data.add("http://wx4.sinaimg.cn/large/5eef6257gy1g8ttfjvbffg20690b4qv5.gif")
                data.add("https://gif.55.la/static/keyword/images/img2.gif")
                data.add("https://gif.55.la/static/keyword/images/img1.gif")
                data.add("https://gif.55.la/static/keyword/images/img4.gif")
                data.add("https://gif.55.la/static/keyword/images/img6.gif")
                for (i in 0 until 9) {

                    val c1 = async(Dispatchers.IO) {
                        Glide.with(it1)
                            .asBitmap()
                            .load(data.get(i))
                            .into(object : SimpleTarget<Bitmap>() {
                                override fun onResourceReady(
                                    resource: Bitmap,
                                    transition: Transition<in Bitmap>?,
                                ) {
                                    val uri = resource.saveToGallery(context!!, resource)
                                    if (uri != null) {
                                        dataUri.add(uri)
                                    }

                                    progress = (dataUri.size / data.size.toFloat())
                                    WaitDialog.show("正在加载" + ((progress * 100).toInt()).toString() + "%",
                                        progress)
                                    if (progress == 1f) {
                                        WaitDialog.dismiss()
                                        //  TipDialog.show(activity,"加载完成", WaitDialog.TYPE.SUCCESS,2000)
                                        if (dataUri.size > 0) {
                                            context?.let {
                                                ShareUtil.sharePictureToWechatFriendUri(it, dataUri, "")
                                                Log.e("TAG", "getFXData: .2222")
                                            }

                                        }
                                    } else {


                                    }
                                    Log.e("TAG", "getFXData: ." + dataUri.size)
                                }


                            })
                        1
                    }
                    dataDeferred.add(c1)

                }
                for (it in dataDeferred) {
                    it.await()
                }
            }


        }
    }


    //乐豆页面
    @LoginCallback
    @RepeatClick
    fun gotoLeDou() {
      //  if (!App.USER_TOKEN.isNullOrEmpty()) {
            navigationTo(RoutePath.MAIN_LEDOU_ACTIVITY)
       /* } else {//登录
            gotoLogin()
        }*/
    }

    //粉丝和关注页面
    @LoginCallback
    @RepeatClick
    fun gotoFansAndGz(typeInfo: String) {
      //  if (!App.USER_TOKEN.isNullOrEmpty()) {
            navigationTo(RoutePath.MAIN_FUN_GZ_ACTIVITY, mutableMapOf(
                Key.DataKey.H5_TITLE to App.userLoginCodeEntity.user.nickname,
                Key.DataKey.FANS_GZ_TYPE to typeInfo.toInt()))
       /* } else {//登录
            gotoLogin()
        }*/


    }

    //个人中心页面
    @LoginCallback
    @RepeatClick
    fun gotoInfo(typeInfo: String) {
     //   if (!App.USER_TOKEN.isNullOrEmpty()) {
            navigationTo(RoutePath.MAIN_INFO_ACTIVITY, mutableMapOf(
                Key.DataKey.INFO_TYPE to typeInfo,
                Key.DataKey.TARGET_USER_ID to App.userLoginCodeEntity.user.userId))
       /* } else {//登录
            gotoLogin()
        }*/


    }

    //设置页面
    @RepeatClick
    fun setting() {
        navigationTo(RoutePath.MAIN_SETTING)

    }

    //公约
    @RepeatClick
    fun gotoGongYue() {
        navigationTo(
            RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                Key.DataKey.H5_TITLE to "隐私协议",
                Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
            )
        )
    }

    //反馈意见
    @RepeatClick
    fun feedback() {
        navigationTo(RoutePath.MAIN_FEEDBACK, mutableMapOf(
            Key.DataKey.H5_TITLE to "反馈意见",
        ))
    }

    //客服
    @RepeatClick
    fun gotoKefu() {
context?.let {
    if (ShareUtil.checkAppInstalled(it, ShareUtil.PACKAGE_MOBILE_QQ)) {
        val url = "mqqwpa://im/chat?chat_type=wpa&uin=1135520344"
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))

    } else {
        Toast.makeText(context, "请先安装QQ客户端", Toast.LENGTH_SHORT).show()
    }
}



    }

    //审核
    @LoginCallback
    @RepeatClick
    fun gotoShenHe(type: String) {
        //if (!App.USER_TOKEN.isNullOrEmpty()) {
            navigationTo(RoutePath.MAIN_FUN_GZ_ACTIVITY, mutableMapOf(
                Key.DataKey.H5_TITLE to if ("0" == type) "审核中" else "审核失败",
                Key.DataKey.FANS_SHENHE_TYPE to type))
        /*} else {//登录
            gotoLogin()
        }*/


    }

    private fun gotoLogin() {
        val onBindView =
            object :
                OnBindView<FullScreenDialog>(R.layout.layout_full_login, true) {
                @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
                override fun onBind(dialog: FullScreenDialog?, v: View?) {
                    val tvPhone = v?.findViewById<EditText>(R.id.edit_userName)
                    v?.findViewById<TextView>(R.id.tv_getCode)//获取验证码
                        ?.setOnClickListener {
                            if (!tvPhone?.text.isNullOrEmpty()) {
                                userViewModel.userLoginGetCode(
                                    this@UserFragment,
                                    tvPhone?.text.toString()
                                ) {
                                    toast(it.msg)
                                } onError {
                                    toast(it)

                                }
                            } else {
                                toast("请输入手机号码！")
                            }

                        }
                    v?.findViewById<TextView>(R.id.tv_loginByOwenPhone)
                        ?.setOnClickListener {
                            getOwnPhone(tvPhone)
                        }

                    val etPsd = v?.findViewById<TextView>(R.id.edit_password)

                    v?.findViewById<ImageView>(R.id.img_qq)
                        ?.setOnClickListener {
                            if (!tvPhone?.text.isNullOrEmpty()) {
                                userViewModel.userPswReset(
                                    this@UserFragment,
                                    etPsd?.text.toString(), "111sam111",
                                    tvPhone?.text.toString()
                                ) {
                                    toast(it.msg)
                                } onError {
                                    toast(it)

                                }
                            } else {
                                toast("请输入手机号码！")
                            }
                        }
                    v?.findViewById<TextView>(R.id.btn_submit)
                        ?.setOnClickListener {
                            if (!tvPhone?.text.isNullOrEmpty()) {
                                if (!etPsd?.text.isNullOrEmpty()) {
                                    userViewModel.userLoginCode(
                                        this@UserFragment,
                                        etPsd?.text.toString(),
                                        tvPhone?.text.toString()
                                    ) {
                                        if (it.code === 200) {
                                            App.USER_TOKEN = it.data.token
                                            //存本地token
                                            ConfigTool.putString(Key.DataKey.TOKEN, it.data.token)
                                            //登录成功
                                            EventBusUtil.sendEvent(Event<Int>(Key.EventKey.EVENT_LOGIN))
                                            dialog?.dismiss()
                                        }
                                    } onError {
                                        toast(it)

                                    }
                                } else {
                                    toast("请输入验证码！")

                                }

                            } else {
                                toast("请输入手机号码！")
                            }
                        }


                    val spannableStringBuilder = SpannableStringBuilder()
                    //设置文字
                    spannableStringBuilder.append("登录/注册代表您同意《用户服务条款》\n和《隐私协议》")
                    //设置文字点击事件（用户协议）
                    spannableStringBuilder.setSpan(object : ClickableSpan() {
                        override fun onClick(widget: View) {
                            navigationTo(
                                RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                    Key.DataKey.H5_TITLE to "用户协议",

                                    Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                )
                            )
                        }
                    }, 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                    //设置文字点击事件（隐私协议）
                    spannableStringBuilder.setSpan(object : ClickableSpan() {
                        override fun onClick(widget: View) {
                            navigationTo(
                                RoutePath.MAIN_H5_ACTIVITY, mutableMapOf(
                                    Key.DataKey.H5_TITLE to "隐私协议",
                                    Key.DataKey.H5_URL to "https://res.villaday.com/static/pages/1907/19/190717-19.html"
                                )
                            )
                        }
                    }, 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                    //设置颜色
                    spannableStringBuilder.setSpan(
                        ForegroundColorSpan(
                            Color.parseColor(
                                "#46AFFF"
                            )
                        ), 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    spannableStringBuilder.setSpan(
                        ForegroundColorSpan(
                            Color.parseColor(
                                "#46AFFF"
                            )
                        ), 20, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    )


                    val tvXieYi = v?.findViewById<TextView>(R.id.tv_xieyi)
                    tvXieYi?.movementMethod = LinkMovementMethod.getInstance()
                    tvXieYi?.text = spannableStringBuilder

                }

            }
        FullScreenDialog.show(onBindView).dialogLifecycleCallback = object :
            DialogLifecycleCallback<FullScreenDialog>() {
            override fun onDismiss(dialog: FullScreenDialog?) {
                super.onDismiss(dialog)

            }

            override fun onShow(dialog: FullScreenDialog?) {
                super.onShow(dialog)
            }

        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    fun getOwnPhone(phone: TextView?) {
        val phoneNumbers =
            context?.let { SIMCardInfo(it).phoneNumberS }
        if (phoneNumbers?.isNotEmpty() == true) {
            for (it in phoneNumbers) {

            }
            phone?.text = phoneNumbers[0]

        } else {
            toast("暂未获取到手机号")
        }


    }

}